package com.huxiu.pagers.zixun;

import android.content.Context;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.huxiu.R;
import com.huxiu.base.ZiXunDetailPager;
import com.huxiu.holder.TuiJianHolder;
import com.huxiu.net.GsonRequest;
import com.huxiu.net.NetworkConstants;
import com.huxiu.net.NetworkHelper;
import com.huxiu.net.model.TuiJianItem;
import com.huxiu.net.responses.TuiJianDataResponse;
import com.huxiu.utils.Constants;
import com.huxiu.utils.ErrorResponseException;
import com.huxiu.utils.Loading;
import com.huxiu.utils.NetUtil;
import com.huxiu.utils.Utils;
import com.huxiu.view.RefreshListView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


public class ShuoZhengJing extends ZiXunDetailPager {

    @ViewInject(R.id.lv_tabdetail_list)
    private RefreshListView lv_tabdetail_list;

    @ViewInject(R.id.loading)
    private LinearLayout loading;// 加载中

    private int myCatid;

    //加载20秒

    @ViewInject(R.id.reLoadView)
    private LinearLayout reLoadView;// 加载中
    private Runnable runnable;
    private Handler handler;

    public ShuoZhengJing(Context context, int position) {
        super(context);
        this.myCatid = position;
    }

    @Override
    protected View initView() {
        View viewAll = View.inflate(mContext, R.layout.list_detail, null);
        ViewUtils.inject(this, viewAll);

        //在oncreat等中实例化
        handler = new Handler();
        runnable = new Runnable() {
            @Override
            public void run() {
                //要做的事情
                reLoadView.setVisibility(View.VISIBLE);
                loading.setVisibility(View.INVISIBLE);
            }
        };
        // 给下拉刷新Listview设置监听器
        lv_tabdetail_list.setOnRefreshingListener(new MyOnRefreshingListener());
        return viewAll;
    }

    class MyOnItemClickListener implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            // 当前Listview加了两个Header，position发生变化了
            int realPosition = position - 2;
            // 获取点击的新闻条目对象
            //            News news = newsData.get(realPosition);
            //            // 获取之前存的id
            //            String cacheId = CacheUtils.getString(mContext, NEWSID_READED_CACHE, "");
            //            String tempID = "";
            //            String currentID = String.valueOf(news.id);
            //            if(!cacheId.contains(currentID)){
            //                tempID = cacheId + "," + currentID;
            //                // 把点击的新闻id存起来
            //                CacheUtils.putString(mContext, NEWSID_READED_CACHE, tempID);
            //                // 通知新闻列表更新界面
            //                adapter.notifyDataSetChanged();
            //            }
            //
            //            // 打开新闻详情界面
            //            Intent intent = new Intent(mContext,NewsDetailUI.class);
            //            intent.putExtra("url", news.url);
            //            mContext.startActivity(intent);
        }

    }

    @Override
    public void initData() {
        if (!NetUtil.checkNet(mContext)) {
            Utils.showToast(R.string.generic_check);
            reLoadView.setVisibility(View.VISIBLE);
            loading.setVisibility(View.INVISIBLE);
            lv_tabdetail_list.setVisibility(View.GONE);
            return;
        } else {
            reLoadView.setVisibility(View.GONE);
            loading.setVisibility(View.VISIBLE);
            lv_tabdetail_list.setVisibility(View.VISIBLE);
        }
        Utils.runOnUIThread(new Runnable() {
            @Override
            public void run() {
                getDataFromServer();
                handler.postDelayed(runnable, Constants.TIME_RELOADE);
            }
        });
    }

    @OnClick({R.id.reLoadView})
    public void mOnClick(View v) {
        switch (v.getId()) {
            case R.id.reLoadView:
                reLoadView.setVisibility(View.GONE);
                loading.setVisibility(View.VISIBLE);
                lv_tabdetail_list.setVisibility(View.VISIBLE);
                initData();
                break;
        }
    }

    private boolean isRefresh = false;// 当前是否是下拉刷新
    private boolean isLoadMore = false;// 当前是否是加载更多

    class MyOnRefreshingListener implements RefreshListView.OnRefreshingListener {
        @Override
        public void onRefreshing() {
            isRefresh = true;
            // 下拉刷新业务
            getDataFromServer();
        }

        @Override
        public void onLoadingMore() {
            if (currentPage <= totalPages) {
                isLoadMore = true;
                // 加载更多业务
                getMoreDataFromServer();
            } else {
                lv_tabdetail_list.loadMoreFinished();
                //                Utils.showToast(R.string.no_more);
                Toast.makeText(mContext, R.string.no_more, Toast.LENGTH_SHORT).show();
            }
        }

    }

    //上拉加载
    private void getMoreDataFromServer() {
        loadList(currentPage + 1);
    }

    //下拉刷新
    private void getDataFromServer() {
        loadList(0);
    }

    private int currentPage = 0;
    private List<TuiJianItem> lists = new ArrayList<>();
    private int totalPages = 0;

    private void loadList(final int page) {
        String url = NetworkConstants.GET_ARTICLE_LIST_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("page", Integer.toString(page));
        params.put("catid", Integer.toString(myCatid));
        GsonRequest<TuiJianDataResponse> request = new GsonRequest<>(url, Request.Method.POST,
                TuiJianDataResponse.class, true, params,
                new Response.Listener<TuiJianDataResponse>() {
                    @Override
                    public void onResponse(TuiJianDataResponse response) {
                        if (response.isSuccess()) {
                            handler.removeCallbacks(runnable);
                            loading.setVisibility(View.INVISIBLE);
                            reLoadView.setVisibility(View.GONE);
                            if (page == 0) {
                                lists.clear();
                            }
                            Collections.addAll(lists, response.data.datalist);
                            currentPage = response.data.cur_page;
                            totalPages = response.data.total_page;
                            parseListJson();
                            // 如果当前是下拉刷新访问的网络，恢复下拉刷新界面
                            if (isRefresh) {
                                lv_tabdetail_list.refreshFinished(true);
                                isRefresh = false;
                            } else if (isLoadMore) {
                                lv_tabdetail_list.loadMoreFinished();
                                isLoadMore = false;

                            }
                        } else {
                            Utils.showToast(response.error.message);
                            // 如果当前是下拉刷新访问的网络，恢复下拉刷新界面
                            if (isRefresh) {
                                lv_tabdetail_list.refreshFinished(false);
                                isRefresh = false;
                            } else if (isLoadMore) {
                                lv_tabdetail_list.loadMoreFinished();
                                isLoadMore = false;
                            }
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Throwable t = error.getCause();
                if (t instanceof ErrorResponseException) {
                    //                Log.e("params", "message" + error.getMessage().toString());
                    Utils.showToast(R.string.generic_failure);
                } else {
                    Utils.showToast(R.string.generic_check_online);
                }
                Loading.closeLoading();
                if (lists != null && lists.size() > 0) {
                    handler.removeCallbacks(runnable);
                }
                // 如果当前是下拉刷新访问的网络，恢复下拉刷新界面
                if (isRefresh) {
                    lv_tabdetail_list.refreshFinished(false);
                    isRefresh = false;
                } else if (isLoadMore) {
                    lv_tabdetail_list.loadMoreFinished();
                    isLoadMore = false;
                }
            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
    }

    private void parseListJson() {
        if (!isLoadMore) {
            adapter = new SpareAdapter();
            lv_tabdetail_list.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
    }

    SpareAdapter adapter;

    private class SpareAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return lists.size();
        }

        @Override
        public Object getItem(int position) {
            return lists.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TuiJianHolder holder;
            View view = convertView;
            if (view == null) {
                view = View.inflate(mContext, R.layout.item_home_list, null);
                holder = new TuiJianHolder(view, mContext);
                view.setTag(holder);
            }
            holder = (TuiJianHolder) view.getTag();
            TuiJianItem item = lists.get(position);
            holder.setAdapter(adapter);
            holder.bindItem(item);//这里用来把获取到的数据传递给holder
            return view;
        }
    }

}
 